<template>
  <div class="app-container">


    <el-tabs type="border-card" style="margin-top: 20px;" @tab-click="onClickTab">
      <el-tab-pane>
        <el-button type="primary" class="el-icon-plus" @click="handleAddRole" :disabled="false">创建角色</el-button>
        <span slot="label"> 角色管理</span>
        <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border>
          <el-table-column align="center" label="ID" width="220">
            <template slot-scope="scope">
              {{ scope.row.id }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="角色名称" width="220">
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="角色编码" width="220">
            <template slot-scope="scope">
              {{ scope.row.kcode}}
            </template>
          </el-table-column>
          <el-table-column align="header-center" label="描述">
            <template slot-scope="scope">
              {{ scope.row.routes }}
            </template>
          </el-table-column>
          <el-table-column align="center" label=操作>
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope)" >编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope)"  :disabled="false">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-tab-pane>
    </el-tabs>

    <el-dialog :visible.sync="dialogVisible"  :title="dialogTitle[dialogType]" :close-on-click-modal=false>
      <el-form ref="formRole" :model="role"   :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="编码：" prop="kcode"  v-if="this.user_role=='RA0001'">
          <el-input v-model="role.kcode" placeholder=""/>
        </el-form-item>
        <el-form-item label="名称：" prop="name">
          <el-input v-model="role.name" placeholder=""/>
        </el-form-item>
<!--        <el-form-item label="组织结构：" prop="">-->
<!--          <el-select v-model="role.organize" placeholder="请选择组织结构">-->
<!--            <el-option v-for="(item,index) in organizeList"-->
<!--                       :label="item.name"-->
<!--                       :value="item.id">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="描述：">
          <el-input
            v-model="role.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="角色描述"
          />
        </el-form-item>
        <el-form-item label="权限：">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :props="defaultProps"
            :show-checkbox="true"
            node-key="id"
            class="permission-tree"
            @check-change="handleCheckChange"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole('formRole')">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible_O" :title="dialogTitle[dialogType]" :close-on-click-modal=false>
      <el-form ref="formOrganize" :rules="rules" :model="organize" label-width="100px" label-position="left">
        <el-form-item label="名称：" prop="name">
          <el-input v-model="organize.name" placeholder="角色名称"/>
        </el-form-item>

        <el-form-item label="描述：" >
          <el-input
            v-model="organize.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="描述"
          />
        </el-form-item>
        <el-form-item label="权限：">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :props="defaultProps"
            show-checkbox
            node-key="path"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible_O=false">取消</el-button>
        <el-button type="primary" @click="confirmOrganize('formOrganize')">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import path from 'path'
  import { deepClone } from '@/utils'
  import { arrMerge, getObjectByProp } from '@/utils/utilc'
  import { getRoutes, getRoles, addRole, deleteRole, updateRole } from '@/api/role'
  import {  getOrganizes, addOrganize, deleteOrganize, updateOrganize } from '@/api/role'
  import { routerListFun } from '@/router/Jurisdiction'
  import { getDynamicRoutes } from '@/router'
  import { mapGetters } from 'vuex'

  const defaultRole = {//这里的数据没啥用，只是让你知道格式
    id: '',          //
    name: '',         //角色名称
    kcode:'',         //角色编码
    description: '',  //描述
    routes: []        //权限
  }

  const defaultOrganize = {//这里的数据没啥用，只是让你知道格式
    id: '',          //
    name: '',         //角色名称
    description: '',  //描述
    routes: []        //权限
  }

  export default {
    data() {
      return {

        rules: {
          kcode: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
          name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
          description: [{ required: true, message: '不能为空', trigger: 'blur' }],

          // order_type: [{ required: true, message: '请选择套餐', trigger: 'blur' }],
          // price: [{ required: true, message: '请输入数字', trigger: 'blur' }, { validator: isInteger, trigger: 'blur' }]
        },
        dialogTitle: ['创建', '编辑'],
        dialogVisible: false,
        dialogVisible_O: false,
        dialogType: '0',

        role: Object.assign({}, defaultRole),
        organize: Object.assign({}, defaultOrganize),

        routes: [],
        rolesList: [],

        organizeList: this.$global.ORGANIZELIST,

        checkStrictly: false,
        defaultProps: {
          children: 'children',
          label: 'title'
        },

        tabsName: [
          { id: 1, name: '角色管理' },
          { id: 2, name: '组织架构' }
        ],
        tabsNameIndex: 0

      }
    },
    computed: {
      routesData() {
        return this.routes
      },
      ...mapGetters([
        'name',
        'avatar',
        'user_organize',
        'user_role',
        'user_routes'
      ]),
    },
    created() {
      // Mock: get all routes and roles list from server
      this.getRoutes()
      this.getRoles()
      // this.getOrganizes()
    },
    methods: {
      async getRoutes() {

        const res = await getRoutes()
        this.serviceRoutes = res.data
        this.routes = this.generateRoutes(res.data)
        // console.log("routes=="+JSON.stringify(this.routes))
        // this.routes = this.generateRoutes(res.data)
      },
       async getRoles() {
        // const res = await getRoles()
        // this.rolesList = res.data

        this.rolesList =  await this.$global.ROLE()

        // console.log("getRoles==="+JSON.stringify(this.rolesList))
        // console.log("g etRoles==="+JSON.stringify(this.rolesList))
      },

      async getOrganizes() {
        const res = await getOrganizes()
        this.organizeList = res.data
      },

      _getObjectByProp(value,prop,array){
       return getObjectByProp(value,prop,array)
      },

      onClickTab(){
        console.log("tabsNameIndex="+this.tabsNameIndex)
        if(this.tabsNameIndex==0){

        }else if(this.tabsNameIndex==1){
          // this.dialogVisible_O = true

        }
      },

      // Reshape the routes structure so that it looks the same as the sidebar
      generateRoutes(routes, basePath = '/') {
        const res = []


        for (let route of routes) {/**/
          // skip some route
          if (route.hidden) {
            continue
          }

          const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

          if (route.children && onlyOneShowingChild && !route.alwaysShow) {
            route = onlyOneShowingChild
          }

          const data = {
            path: path.resolve(basePath, route.path),
            title: route.meta && route.meta.title+"="+route.id,
            id:route.id

          }

          // recursive child routes
          if (route.children) {
            data.children = this.generateRoutes(route.children, data.path)
          }
          res.push(data)
        }
        return res
      },
      generateArr(routes) {
        let data = []
        routes.forEach(route => {
          data.push(route)
          if (route.children) {
            const temp = this.generateArr(route.children)
            if (temp.length > 0) {
              data = [...data, ...temp]
            }
          }
        })
        return data
      },
      handleAddRole() {
        this.role = Object.assign({}, defaultRole)
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedNodes([])
        }
        this.dialogType = '0'
        this.dialogVisible = true
      },
      handleAddOrganize(){
        this.organize = Object.assign({}, defaultOrganize)
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedNodes([])
        }
        this.dialogType = '0'
        this.dialogVisible_O = true

      },
      handleEdit(scope) {
        this.dialogType = '1'
        this.dialogVisible = true
        this.checkStrictly = true
        this.role = deepClone(scope.row)

        // console.log("arr=="+JSON.stringify(this.role))
        let arr = this.role.routes.split(',')
        arr.forEach(function(value,index,arr){

         arr[index]= parseInt(value)

        })

        let dpDynamicRoutes = getDynamicRoutes()
        console.log("arr=="+JSON.stringify(dpDynamicRoutes))
        // let arr = [1,11,2,21,22,3,31,4,41,42,43,431,432,5,51,6,61]   //权限列表数组
        // let arr = [2,21,22,3,31,4,43,431,5,51]   //权限列表数组

        this.role.routes = routerListFun(arr,dpDynamicRoutes)

        // console.log("arr=="+JSON.stringify(this.role.routes))


        if(this.role.routes){
          this.$nextTick(() => {
            const routes = this.generateRoutes(this.role.routes)
            // this.$refs.tree.setCheckedNodes(this.generateArr(routes))
            this.$refs.tree.setCheckedKeys(arr)
            // set checked state of a node not affects its father and child nodes
            this.checkStrictly = false
          })
        }

      },

      handleEditOrganize(scope) {
        this.dialogType = '1'
        this.dialogVisible_O = true
        this.checkStrictly = true
        this.organize = deepClone(scope.row)
        this.$nextTick(() => {
          const routes = this.generateRoutes(this.role.routes)
          this.$refs.tree.setCheckedNodes(this.generateArr(routes))
          // set checked state of a node not affects its father and child nodes
          this.checkStrictly = false
        })
      },

      handleDelete({ $index, row }) {
        this.$confirm('确定要删除角色吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
            await deleteRole(row.kcode)
            this.rolesList.splice($index, 1)
            this.$message({
              type: 'success',
              message: 'Delete succed !'
            })
          })
          .catch(err => {
            console.error(err)
          })
      },

      handleDeleteOrganize({ $index, row }) {
        this.$confirm('确定要删除数据吗?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            await deleteOrganize(row.id)
            this.organizeList.splice($index, 1)
            this.$message({
              type: 'success',
              message: 'Delete succed !'
            })
          })
          .catch(err => {
            console.error(err)
          })
      },


      generateTree(routes, basePath = '/', checkedKeys) {
        const res = []

        for (const route of routes) {
          const routePath = path.resolve(basePath, route.path)

          // recursive child routes
          if (route.children) {
            route.children = this.generateTree(route.children, routePath, checkedKeys)
          }

          if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
            res.push(route)
          }
        }
        return res
      },
      async confirmRole(formRole) {

        //只是主分支

        let bool =false
          this.$refs[formRole].validate((valid) => {
          if (valid) {
            bool= true
          } else {
            this.$message('error submit!!')
            bool= false
          }
        })

        if (!bool) {
          return
        }



        const isEdit = this.dialogType === '1'

        // const checkedKeys = this.$refs.tree.getCheckedKeys()
        let checkedKeys = this.$refs.tree.getCheckedKeys()
        let checkedHalfKeys = this.$refs.tree.getHalfCheckedKeys()

        // console.log("checkedKeys=="+checkedHalfKeys.toString())
        // console.log("checkedKeys=="+checkedKeys.toString())

        const checkAllKeys = arrMerge(checkedKeys,checkedHalfKeys)

        // this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)


        this.role.routes = checkAllKeys.toString()

        if (isEdit) {
          await updateRole(this.role.id, this.role)
          for (let index = 0; index < this.rolesList.length; index++) {
            if (this.rolesList[index].id === this.role.id) {
              this.rolesList.splice(index, 1, Object.assign({}, this.role))
              break
            }
          }
        } else {
          const { data } = await addRole(this.role)
          // console.log("rolesList.key=="+data.key)

          this.role.id = data.id
          this.rolesList.push(this.role)

          // console.log("rolesList=="+JSON.stringify(this.rolesList))

        }

        const { description, id, name } = this.role
        this.dialogVisible = false
        this.$notify({
          title: 'Success',
          dangerouslyUseHTMLString: true,
          message: `
            <div>ID: ${id}</div>
            <div>名称: ${name}</div>
            <div>描述: ${description}</div>
          `,
          type: 'success'
        })
      },

      async confirmOrganize(formOrganize) {
        let bool = false
         this.$refs[formOrganize].validate((valid) => {
          if (valid) {
            bool = true;

          } else {
            this.$message('error submit!!')
            bool = false;
          }
        })
        if (!bool) {

          return
        }
        const isEdit = this.dialogType === '1'

        const checkedKeys = this.$refs.tree.getCheckedKeys()
        this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)

        if (isEdit) {
          await updateOrganize(this.organize.id, this.organize)

          for (let index = 0; index < this.organizeList.length; index++) {
            if (this.organizeList[index].id === this.organize.id) {
              this.organizeList.splice(index, 1, Object.assign({}, this.organize))
              break
            }
          }
        } else {
          const { data } = await addOrganize(this.organize)
          this.organize.id = data.id
          this.organizeList.push(this.organize)

          console.log("organizeList="+JSON.stringify(this.organizeList))
        }

        const { description, id, name } = this.organize
        this.dialogVisible_O = false
        this.$notify({
          title: 'Success',
          dangerouslyUseHTMLString: true,
          message: `
            <div>ID: ${id}</div>
            <div>名称: ${name}</div>
            <div>描述: ${description}</div>
          `,
          type: 'success'
        })
      },

      // reference: src/view/layout/components/Sidebar/SidebarItem.vue
      onlyOneShowingChild(children = [], parent) {
        let onlyOneChild = null
        const showingChildren = children.filter(item => !item.hidden)

        // When there is only one child route, the child route is displayed by default
        if (showingChildren.length === 1) {
          onlyOneChild = showingChildren[0]
          onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
          return onlyOneChild
        }

        // Show parent if there are no child route to display
        if (showingChildren.length === 0) {
          onlyOneChild = { ...parent, path: '', noShowingChildren: true }
          return onlyOneChild
        }

        return false
      },

      handleCheckChange(data, checked, indeterminate) {
        console.log(data, checked, indeterminate);
      },
    }
  }
</script>

<style lang="scss" scoped>
  .app-container {
    .roles-table {
      margin-top: 30px;
    }

    .permission-tree {
      margin-bottom: 30px;
    }
  }


</style>
<style>
  .el-table th {
    display: table-cell !important;
  }
</style>
